﻿﻿<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resources/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resources/easyui/themes/icon.css">
    <script type="text/javascript" src="<%=request.getContextPath() %>/resources/easyui/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath() %>/resources/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath() %>/resources/easyui/locale/easyui-lang-zh_CN.js"></script>
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/resources/style/main.css">
    <script type="text/javascript">


        //密码输入框组件
        $.extend($.fn.datagrid.defaults.editors, {
            password: {
                init: function(container, options){
                    var input = $('<input type="password" class="datagrid-editable-input">').appendTo(container);
                    return input;
                },
                destroy: function(target){
                    $(target).remove();
                },
                getValue: function(target){
                    return $(target).val();
                },
                setValue: function(target, value){
                    $(target).val(value);
                },
                resize: function(target, width){
                    $(target)._outerWidth(width);
                }
            }
        });

        var userlist = <%=request.getAttribute("userJson")%>;
        var groupTreeList= <%=request.getAttribute("groupTreeJson")%>;
        var grouplist= <%= request.getAttribute("groupJson")%>;
        var UrlConfig = {
            SysUserList: '<%=request.getContextPath() %>/user/list',
            SysUserPage: '<%=request.getContextPath() %>/user/page',
            SysUserAdd: '<%=request.getContextPath() %>/user/add',
            SysUserUpdate: '<%=request.getContextPath() %>/user/update',
            SysUserDelete: '<%=request.getContextPath() %>/user/deleteByName',
            SysUserResetPassword: '<%=request.getContextPath() %>/user/resetPassword',
            SysRoleList: '<%=request.getContextPath() %>/role/list',
            SysGroupList: '<%=request.getContextPath() %>/group/list',
            SysGroupAdd: '<%=request.getContextPath() %>/group/add',
            SysGroupUpdate: '<%=request.getContextPath() %>/group/update',
            SysGroupDelete: '<%=request.getContextPath() %>/group/delete',
            SysGroupTree:'<%=request.getContextPath() %>/group/tree'
        };
        var url;
        var roles = [
            {roleId:1,roleName:'系统管理员'},
            {roleId:2,roleName:'数据区管理员'},
            {roleId:3,roleName:'工程师'},
            {roleId:4,roleName:'阅览者'}
        ];

        //用于保存user数据修改的buffer
        var changeBuffer = new Array();

        function roleFormatter(value){
            for(var i=0;i<roles.length;i++){
                if(roles[i].roleId==value)
                    return roles[i].roleName;
            }
            return 0;
        }
        function groupFormatter(value){
            if(value==0){
                return '*待分配*'
            }
            for(var i=0;i<grouplist.length;i++){
                if(grouplist[i].groupId==value)
                    return grouplist[i].groupName;
            }
            return value;
        }

        var editIndex = undefined;
        function endEditing(){
            if (editIndex == undefined){return true}
            if ($('#dg').datagrid('validateRow', editIndex)){
                var red = $('#dg').datagrid('getEditor', {index:editIndex,field:'roleId'});
                var rolename=$(red.target).combobox('getText');
                $('#dg').datagrid('getRows')[editIndex]['roleName']=rolename;
                var ed = $('#dg').datagrid('getEditor', {index:editIndex,field:'groupId'});
                var groupname=$(ed.target).combobox('getText');
                $('#dg').datagrid('getRows')[editIndex]['groupName']=groupname;
                $('#dg').datagrid('endEdit',editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        }

        function onEndEdit(index, row, changes){
            var data = {id:row['id']};
            for(key in changes) {
                data[key] = changes[key];
            }

            for(key in row){
                if(data[key] == undefined){
                    data[key] = row[key];
                }
            }
            changeBuffer[row['id']] = data;
        }

        function onClickRow(index){
            if (editIndex != index){
                if (endEditing()){
                    $('#dg').datagrid('selectRow', index)
                            .datagrid('beginEdit', index);
                    editIndex = index;
                    //刷新combobox
                    $("#dg").datagrid('getEditors',index)[3].target.combobox('reload',UrlConfig.SysGroupList);
                } else {
                    $('#dg').datagrid('selectRow', editIndex);
                }
            }
        }
        function append(){
            if (endEditing()){
                $('#dg').datagrid('appendRow',{roleName:'工程师',groupName:'软工工程所'});
                editIndex = $('#dg').datagrid('getRows').length-1;
                $('#dg').datagrid('selectRow', editIndex)
                        .datagrid('beginEdit', editIndex);
            }
            url=UrlConfig.SysUserAdd;
        }

        function removeit(){
            if (editIndex == undefined){return}
            if ($('#dg').datagrid('validateRow', editIndex)){
                var username=$('#dg').datagrid('getSelected')["userName"];
                $.messager.confirm('Confirm','确认删除该用户？',function(n){
                    if(n){
                        $.post(UrlConfig.SysUserDelete,{userName:username},function(result){
                            $('#dg').datagrid('cancelEdit', editIndex)
                                    .datagrid('deleteRow', editIndex);
                            editIndex = undefined;
                        });
                    }
                });
            }
        }
        function accept(){

            $('#dg').datagrid('acceptChanges');
            if(editIndex==undefined){return}
            if($('#dg').datagrid('validateRow',editIndex)){
                var row = $('#dg').datagrid('getRows')[editIndex];

                var data={id:row['id'],userName:row['userName'],password:row['password'],
                    roleId:row['roleId'],groupId:row['groupId']};

                //默认是修改
                if(url == undefined) {
                    url=UrlConfig.SysUserUpdate;
//                    data = new Array();
//                    for(key in changeBuffer){
//                        data.push(changeBuffer[key]);
//                    }
                }
                $.get(url,data,function(result){
                    result=eval(result);
                    if(result.successful){
                        $.messager.show({title:'操作结果',msg:'操作成功'});
                    }else{
                        var msg= '操作失败';
                        if(result.message== 'user name exists'){
                            msg='用户名已经存在';
                        }
                        $.messager.show({title:'操作结果',msg:msg});
                    }
                    url=undefined;
                    reload();
                });
            }
            url=undefined;
            editIndex=undefined;
        }
        function reject(){
            $('#dg').datagrid('rejectChanges');
            editIndex = undefined;
        }

        function newGroup() {
            var node = $('#group_tree').tree('getSelected');
            if (node) {
                $('#group_save_dialog').dialog('open').dialog('setTitle', '添加群组');
                $('#group_info_form').form('clear');
                url = UrlConfig.SysGroupAdd;
            } else {
                if (!isTreeEmpty())
                    $.messager.alert("操作提示","请选择节点","warning");
                else {
                    $('#group_save_dialog').dialog('open').dialog('setTitle', '添加目录');
                    $('#group_info_form').form('clear');
                    url = UrlConfig.SysGroupAdd;
                }
            }
        }
        function isTreeEmpty(){
            var root=$('#group_tree').tree('getRoot');
            return root == null;
        }

        function editGroup(){
            var node=$('#group_tree').tree('getSelected');
            if(node){
                $("input[name='groupName']").prop('value',node.attributes.groupName);
                $("#group_save_dialog").dialog('open').dialog('setTitle','编辑群组');
                url=UrlConfig.SysGroupUpdate;
            }else{
                if(!isTreeEmpty()) {
                    $.messager.alert("操作提示","请选择节点","warning");
                    return;
                }
                $.messager.alert("操作提示","请先添加群组","warning");
            }
        }

        function saveGroup(){
            var node=$('#group_tree').tree('getSelected');
            var name=$("input[name='groupName']")[0].value;

            var groupId = null;
            var data = {groupName:name};
            if(node==null){
                data['parentId'] = 0;
            }else {
                if (url == UrlConfig.SysGroupUpdate) {
                    data['groupId'] = node.attributes.groupId;
                    data['parentId'] = node.attributes.parentId;

                } else if (url == UrlConfig.SysGroupAdd) {
                    data['parentId'] = node.attributes.groupId;
                }
            }

            $.get(url,data, function (result) {
                result=eval(result);
                if(result.successful){
                    $('#group_save_dialog').dialog('close');
                    reload();
                    $.messager.show({title:'操作结果',msg:'操作成功'});
                }else{
                    $.messager.show({title:'操作结果',msg:'操作失败'});
                }
                url=undefined;
            });
        }

        function destroyGroup(){
            var node= $("#group_tree").tree('getSelected');
            if(node){
                if($('#group_tree').tree('isLeaf',node.target)){
                    $.messager.confirm('Confirm','请确认删除该节点？', function (n){
                                if(n){
                                    $.post(UrlConfig.SysGroupDelete,{groupId:node.attributes.groupId},function(result){
                                        $.messager.show({title:'操作结果',msg:'操作成功'});
                                        reload();
                                    })
                                }
                            }
                    );
                }else{
                    $.messager.alert("操作提示","请从叶子节点开始删除","warning");
                }
            } else {
                $.messager.alert("操作提示","请选择节点","warning");
            }
        }

        function reload(){
            var newData;
            $.get(UrlConfig.SysGroupTree,{},function(result){
                newData=eval(result);
                $('#group_tree').tree({
                    data:newData
                })
            });

            $.get(UrlConfig.SysUserList,{},function(result){
                //清空
                var dg = $('#dg');
                var item = dg.datagrid('getRows');
                if (item) {
                    for (var i = item.length - 1; i >= 0; i--) {
                        var index = dg.datagrid('getRowIndex', item[i]);
                        dg.datagrid('deleteRow', index);
                    }
                }

                var users=eval(result);
                dg.datagrid({
                    data:users
                });
            });

        }

    </script>
    <title>系统管理</title>
</head>
<body>
<table width=100% border="0" cellpadding="0" cellspacing="0">
    <tr height="60px" style="background:url('<%=request.getContextPath() %>/resources/images/utitle.png');
    background-position: center center;  background-repeat: repeat;">
        <td width="2%"></td>
        <td width=5% valign="top" ><img src="resources/images/ulogo.png" width="63" height="57" /></td>
        <td width=73% valign="top" align="left">
            <div align="justify" >
                <p style="font-size:24px;font-family:SimSun-ExtB; font-weight: bold">|主模型策划平台</p>
            </div></td>
        <td width=20% valign="middle" class="STYLE4">
            <div align="justify" >
                <TextBox style="font-weight: bold; font-size: 14px; font-family: SimSun-ExtB">
                    欢迎你：${currentUser.userName}
                </TextBox>
                <a  href="<%=request.getContextPath() %>/logout"><button style=" font-family: SimSun-ExtB" border-rdius="2px">退出</button></a>
            </div>
        </td>
    </tr>
    <tr style="background-color: #a0bfd3">
        <td align="center" id="bg_td" width="100%" height="600" colspan="4" valign="top" class="STYLE4">
            <div id="p" class="easyui-panel" title="系统管理" iconCls='icon-edit' style="width:800px;height:650px;">
                <div id="tabs" class="easyui-tabs" style="width:770px;height:600px">
                    <div id="user-manage" title="用户管理" style="padding:10px">
                        <table id="dg" class="easyui-datagrid" style="width:700px;height:540px"
                               data-options="
				iconCls: 'icon-edit',
				singleSelect: true,
				toolbar: '#tb',
				data:userlist,
				method: 'get',
				onClickRow: onClickRow,
				onAfterEdit:onEndEdit,
				rownumbers:true,
				pagination:true
			">
                            <thead>
                            <tr>
                                <th data-options="field:'userName',width:150,editor:{
                        type:'text',
                        options:{
                            required:true
                        }
                    }">用户名称</th>
                                <th data-options="field:'password',width:150,editor:{type:'password'}">重置密码</th>
                                <th data-options="field:'roleId',width:185,
						formatter:roleFormatter,
						editor:{
							type:'combobox',
							options:{
								valueField:'roleId',
								textField:'roleName',
								data:roles,
								required:true
							}
						}">用户角色</th>

                                <th id="groupId" data-options="field:'groupId',width:185,
						formatter:groupFormatter,
						editor:{
							type:'combobox',
							options:{
								valueField:'groupId',
								textField:'groupName',
								method:'get',
								data:grouplist,
							}
						}">用户群组</th>
                            </tr>
                            </thead>
                        </table>

                        <div id="tb" style="height:auto">
                            <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="append()">添加</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="removeit()">删除</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true" onclick="accept()">保存</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-undo',plain:true" onclick="reject()">撤销</a>
                        </div>

                    </div>
                    <div id="group-manage" title="群组管理" style="padding:10px">
                        <div>
                            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newGroup()">添加</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editGroup()">修改</a>
                            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyGroup()">删除</a>
                        </div>
                        <div id="group_tree" class="easyui-tree"></div>
                        <div id="group_save_dialog" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
                             closed="true" button="#group_save_dialog_buttons" modal="true">
                            <div class="ftitle">输入节点信息</div>
                            <div id="group_info_form">
                                <lable>群组名称：</lable>
                                <input type="text" name="groupName" required="true"/>
                            </div>
                            <div >
                                <lable></lable>
                            </div>
                            <div id="group_save_dialog_buttons">
                                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveGroup()">保存</a>
                                <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#group_save_dialog').dialog('close')">取消</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </td>
    </tr>
</table>

<script type="text/javascript">
    //加载群组数据
    reload();
</script>

</body>
</html>